package com.greendragon.web.action.account; 

import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.validation.SkipValidation;

import com.greendragon.control.constant.GlobalConstants;
import com.greendragon.persistence.domain.User;
import com.greendragon.service.frontend.IUserFrontendService;
import com.greendragon.web.action.BaseAction;
import com.greendragon.web.view.SecurityQuestion;
import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;

/** 
 * @author wulibin, exceptsky@gmail.com, 2011-11-15 下午08:12:41
 * 
 */
public class RetakePasswordByAnswerAction extends BaseAction{
	private static final long serialVersionUID = -1220102350236765748L;
	
	private static Logger          	logger           = Logger.getLogger(RetakePasswordByAnswerAction.class);
	private IUserFrontendService   	userService;
	private ImageCaptchaService    	captchaService;
	
    private String                	name;
	private String 					token;
	private String 					captcha;
    
    public String execute() throws Exception {
    	User user = userService.getByName(name);
        if (null == user) {
            addFieldError("name", getText("email.notExist"));
            return INPUT;
        }
        getSession().put(GlobalConstants.SESSION_FORGET_PASSWORD_USER, user);

        String questionId = user.getSecurityQuestion();
        String question = null;
        if(null != questionId){
        	question = SecurityQuestion.getQuestion(questionId);
        }
        getSession().put(GlobalConstants.SESSION_QUESTION, question);
        return SUCCESS;
    }

    @SkipValidation
    public void validate() {
    	//已经有错误，就不再校验
    	if(getFieldErrors().size()!=0){
    		return;
    	}
    	
    	if(token!=null){
    		//校验验证码
   		 Boolean isResponseCorrect = Boolean.FALSE;
            try {
                isResponseCorrect = captchaService.validateResponseForID(token,captcha.toUpperCase());
                if(!isResponseCorrect){
               	 	addFieldError("captcha", getText("captcha.fail"));
                }
            } catch (CaptchaServiceException e) {
           	 	logger.error(e);
           	 	addFieldError("captcha", getText("captcha.fail"));
            }
    	}else{
    		addFieldError("captcha", getText("captcha.fail"));
    	}
    }

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setUserService(IUserFrontendService userService) {
		this.userService = userService;
	}

	public void setCaptchaService(ImageCaptchaService captchaService) {
		this.captchaService = captchaService;
	}

	public void setCaptcha(String captcha) {
		this.captcha = captcha;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String getCaptcha() {
		return captcha;
	}
	
	
}
 